package com.example.demo.service;

import com.example.demo.model.Student;
import com.example.demo.model.User;
import com.example.demo.model.College;
import com.example.demo.model.Major;
import com.example.demo.model.Classes;
import com.example.demo.model.ClassStudent; // 添加导入
import com.example.demo.repository.StudentRepository;
import com.example.demo.repository.UserRepository;
import com.example.demo.repository.CollegeRepository;
import com.example.demo.repository.MajorRepository;
import com.example.demo.repository.ClassRepository;
import com.example.demo.repository.ClassStudentRepository; // 添加导入
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.time.Year;
import java.time.LocalDateTime;

@Service
public class StudentService {
    @Autowired
    private StudentRepository studentRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private CollegeRepository collegeRepository;
    
    @Autowired
    private MajorRepository majorRepository;
    
    @Autowired
    private ClassRepository classRepository;
    
    @Autowired
    private ClassStudentRepository classStudentRepository; // 添加注入

    public Page<Student> getAllStudents(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Student> studentPage = studentRepository.findAll(pageable);
        // 为每个学生填充用户信息和关联信息
        return studentPage.map(this::populateStudentFullInfo);
    }
    
    private Student populateStudentFullInfo(Student student) {
        // 填充用户信息
        if (student.getUserId() != null) {
            Optional<User> userOpt = userRepository.findById(student.getUserId());
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                student.setName(user.getRealName());
                student.setEmail(user.getUsername()); // 使用用户名作为邮箱
                student.setPhone(""); // 用户表中没有电话字段
                student.setCreatedAt(user.getCreatedAt());
                student.setGender(user.getGender() != null ? user.getGender().name() : ""); // 设置性别信息
            }
        }
        
        // 填充学院信息
        if (student.getCollegeId() != null) {
            Optional<College> collegeOpt = collegeRepository.findById(student.getCollegeId());
            if (collegeOpt.isPresent()) {
                student.setCollegeName(collegeOpt.get().getName());
            }
        }
        
        // 填充专业信息
        if (student.getMajorId() != null) {
            Optional<Major> majorOpt = majorRepository.findById(student.getMajorId());
            if (majorOpt.isPresent()) {
                student.setMajorName(majorOpt.get().getName());
            }
        }
        
        // 填充班级信息
        if (student.getClassId() != null) {
            Optional<Classes> classOpt = classRepository.findById(student.getClassId());
            if (classOpt.isPresent()) {
                student.setClassName(classOpt.get().getName());
            }
        }
        
        return student;
    }

    public Optional<Student> getStudentById(Long id) {
        Optional<Student> studentOpt = studentRepository.findById(id);
        if (studentOpt.isPresent()) {
            Student student = studentOpt.get();
            populateStudentFullInfo(student);
            return Optional.of(student);
        }
        return studentOpt;
    }

    public Student saveStudent(Student student) {
        // 检查是否是新增学生还是更新学生
        boolean isNew = student.getId() == null;
        Long oldClassId = null;
        
        // 如果是更新学生，获取更新前的班级ID
        if (!isNew) {
            Optional<Student> existingStudentOpt = studentRepository.findById(student.getId());
            if (existingStudentOpt.isPresent()) {
                oldClassId = existingStudentOpt.get().getClassId();
            }
        }
        
        // 保存学生信息
        Student savedStudent = studentRepository.save(student);
        
        // 更新班级学生计数和class_students关联表
        updateClassStudentCount(oldClassId, student.getClassId(), savedStudent.getId(), isNew);
        
        return savedStudent;
    }

    public void deleteStudent(Long id) {
        // 获取要删除的学生信息
        Optional<Student> studentOpt = studentRepository.findById(id);
        if (studentOpt.isPresent()) {
            Student student = studentOpt.get();
            // 删除学生
            studentRepository.deleteById(id);
            // 更新班级学生计数和class_students关联表
            updateClassStudentCount(student.getClassId(), null, id, false);
        }
    }

    /**
     * 更新班级学生计数
     * @param oldClassId 原班级ID（可为null）
     * @param newClassId 新班级ID（可为null）
     * @param studentId 学生ID
     * @param isNew 是否为新增学生
     */
    private void updateClassStudentCount(Long oldClassId, Long newClassId, Long studentId, boolean isNew) {
        // 如果原班级和新班级相同，则无需更新
        if (oldClassId != null && oldClassId.equals(newClassId) && !isNew) {
            return;
        }
        
        // 删除原班级的学生关联记录
        if (oldClassId != null) {
            // 删除class_students表中的关联记录
            List<ClassStudent> oldClassStudents = classStudentRepository.findByClassIdAndStudentId(oldClassId, studentId);
            for (ClassStudent cs : oldClassStudents) {
                classStudentRepository.delete(cs);
            }
            
            // 更新班级学生计数
            classRepository.findById(oldClassId).ifPresent(oldClass -> {
                Integer count = oldClass.getStudentCount();
                if (count == null) {
                    count = 0;
                }
                oldClass.setStudentCount(Math.max(0, count - 1)); // 确保不会小于0
                classRepository.save(oldClass);
            });
        }
        
        // 添加新班级的学生关联记录
        if (newClassId != null) {
            // 先检查是否已存在关联记录
            List<ClassStudent> existingClassStudents = classStudentRepository.findByClassIdAndStudentId(newClassId, studentId);
            if (existingClassStudents.isEmpty()) {
                // 添加class_students表中的关联记录
                ClassStudent classStudent = new ClassStudent(newClassId, studentId);
                classStudentRepository.save(classStudent);
            }
            
            // 更新班级学生计数
            classRepository.findById(newClassId).ifPresent(newClass -> {
                Integer count = newClass.getStudentCount();
                if (count == null) {
                    count = 0;
                }
                newClass.setStudentCount(count + 1);
                classRepository.save(newClass);
            });
        }
    }

    public Optional<Student> getStudentByStudentNo(String studentNo) {
        Optional<Student> studentOpt = studentRepository.findByStudentNo(studentNo);
        if (studentOpt.isPresent()) {
            Student student = studentOpt.get();
            populateStudentFullInfo(student);
            return Optional.of(student);
        }
        return studentOpt;
    }

    public Optional<Student> getStudentByUserId(Long userId) {
        Optional<Student> studentOpt = studentRepository.findByUserId(userId);
        if (studentOpt.isPresent()) {
            Student student = studentOpt.get();
            populateStudentFullInfo(student);
            return Optional.of(student);
        }
        return studentOpt;
    }
    
    // 根据班级ID获取学生列表
    public List<Student> getStudentsByClassId(Long classId) {
        List<Student> students = studentRepository.findByClassId(classId);
        // 为每个学生填充用户信息和关联信息
        return students.stream().map(this::populateStudentFullInfo).collect(java.util.stream.Collectors.toList());
    }
    
    // 根据班级ID获取学生列表（分页）
    public Page<Student> getStudentsByClassId(Long classId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Student> studentPage = studentRepository.findByClassId(classId, pageable);
        // 为每个学生填充用户信息和关联信息
        return studentPage.map(this::populateStudentFullInfo);
    }
    
    // 获取所有学生用于导出
    public List<Student> getAllStudentsForExport() {
        List<Student> students = studentRepository.findAll();
        // 为每个学生填充用户信息和关联信息
        return students.stream().map(this::populateStudentFullInfo).collect(java.util.stream.Collectors.toList());
    }
    
    // 添加分页搜索方法
    public Page<Student> searchStudents(String studentNo, String name, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        if (studentNo != null && !studentNo.isEmpty()) {
            studentNo = "%" + studentNo + "%";
        } else {
            studentNo = null;
        }
        
        if (name != null && !name.isEmpty()) {
            name = "%" + name + "%";
        } else {
            name = null;
        }
        
        if (studentNo != null || name != null) {
            return studentRepository.findByStudentNoContainingAndNameContaining(studentNo, name, pageable);
        } else {
            return studentRepository.findAll(pageable);
        }
    }
}